package com.reggie.background.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.background.common.R;
import com.reggie.background.dto.DishDto;
import com.reggie.background.entity.Category;
import com.reggie.background.entity.Dish;
import com.reggie.background.entity.DishFlavor;
import com.reggie.background.service.CategoryService;
import com.reggie.background.service.DishFlavorService;
import com.reggie.background.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 添加菜品
     *
     * @param dishdto
     * @return
     */
    @CacheEvict(value="dishCache",allEntries = true)
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishdto) {
        boolean result = dishService.saveDishDao(dishdto);
        if (result) {
            return R.success("菜品添加成功！");
        }
        return R.error("菜品添加失败！");
    }

    /**
     * 获取菜品分页列表
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        qw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, qw);
        Page<DishDto> page2 = new Page<>(page, pageSize);
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> collect = records.stream().map(item -> {
            DishDto dishdto = new DishDto();
            BeanUtils.copyProperties(item, dishdto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishdto.setCategoryName(category.getName());
            return dishdto;
        }).collect(Collectors.toList());
        page2.setRecords(collect);
        page2.setTotal(pageInfo.getTotal());
        return R.success(page2);
    }

    /**
     * 停售/启售菜品
     *
     * @param statement
     * @param ids
     * @return
     */
    @CacheEvict(value="dishCache",allEntries = true)
    @PostMapping("/status/{statement}")
    public R<String> changeStatus(@PathVariable int statement, Long[] ids) {
        List<Dish> collect = Arrays.stream(ids).map(item -> {
            Dish dish = new Dish();
            dish.setId(item);
            dish.setStatus(statement);
            return dish;
        }).collect(Collectors.toList());
        boolean result = dishService.updateBatchById(collect);
        if (result) {

            return R.success("菜品停售成功!");
        }
        return R.error("菜品停售失败!");
    }

    /**
     * 根据id获取菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getByid(@PathVariable(name = "id") Long id) {
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(qw);
        DishDto dishdto = new DishDto();
        BeanUtils.copyProperties(dish, dishdto);
        dishdto.setFlavors(list);
        return R.success(dishdto);
    }

    /**
     * 更新菜品和菜品口味
     *
     * @param dishdto
     * @return
     */
    @CacheEvict(value="dishCache",allEntries = true)
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishdto) {
        boolean result = dishService.updateDishDao(dishdto);
        if (result) {
            return R.success("菜品更新成功！");
        } else {
            return R.success("菜品更新失败！");
        }
    }

    /**
     * 根据菜品分类id和状态查询菜品列表
     * @param dish
     * @return
     */
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.status")
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        //根据菜品分类id和在售状态获取菜品列表
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        query.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        query.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(query);

        List<DishDto> collect = list.stream().map(item -> {
            //根据菜品id获取菜品口味
            DishDto dishdto = new DishDto();
            BeanUtils.copyProperties(item, dishdto);
            LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
            qw.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qw);
            dishdto.setFlavors(list1);
            return dishdto;
        }).collect(Collectors.toList());


        return R.success(collect);
    }
}
